import { forwardRef, useImperativeHandle } from 'react';
import { useSafeState, useMemoizedFn, useMount } from 'ahooks';
import DialogContent from "../Dialog/content";
import type { OpenDialogWrapperProps, OpenDialogWrapperRefs } from './types';

const OpenDialogWrapper = forwardRef<OpenDialogWrapperRefs, OpenDialogWrapperProps>((props, ref) => {
  const { afterClose, canClose, children, ...rest } = props;
  const [open, setOpen] = useSafeState(false);

  const handleClose = useMemoizedFn(() => {
    if (canClose?.() ?? true) {
      setOpen(false);
    }
  });

  useMount(() => setOpen(true));

  useImperativeHandle(ref, () => {
    return { close: handleClose };
  });

  return (
    <DialogContent
      {...rest}
      open={open}
      onClose={handleClose}
      afterClose={afterClose}
    >
      {children}
    </DialogContent>
  );
})

export default OpenDialogWrapper;